import {Button, ConfigProvider, Image, Layout, message, Popover, Space} from "antd";
import {SketchPicker} from "react-color";
import {EditOutlined, PoweroffOutlined, UserOutlined} from "@ant-design/icons";
import {getLocalValue, getLoginName, getLoginObj, removeToken, setLocalValue} from "../../utils/LocaStorage";
import {useState} from "react";
import {ModalForm, ProForm, ProFormText} from "@ant-design/pro-components";
import {waitTime} from "../../utils/Const";
import {request} from "../../utils/Http";
import {useNavigate} from "react-router-dom";
import logo from "../../logo.svg"

const {Header} = Layout;

const CustomHeader = () => {
    const navigate = useNavigate();
    // 主题色
    const [color, setColor] = useState({
        primaryColor: '#1890ff',
        errorColor: '#ff4d4f',
        warningColor: '#faad14',
        successColor: '#52c41a',
        infoColor: '#1890ff',
    });
    // 主题色是否被更改
    const colorChange = JSON.parse(getLocalValue('color'))
    // 检测是否更改主题色
    if (colorChange) {
        ConfigProvider.config({
            theme: colorChange,
        });
    }
    const onColorChange = (nextColor) => {
        const mergedNextColor = {...color, ...nextColor};
        setColor(mergedNextColor);
        setLocalValue('color', JSON.stringify(mergedNextColor))
        ConfigProvider.config({
            theme: mergedNextColor,
        });
    };
    return (
        <Header style={{
            textAlign: 'center',
            height: 64,
            paddingInline: 48,
            lineHeight: '64px',
            backgroundColor: '#fff',
            padding: '0px 10px'
        }}>
            <div className="logo" style={{
                float: 'left',
                width: '90px',
            }}><Image src={logo} preview={false}/>
            </div>
            <Space
                size={12}
                style={{
                    float: 'right',
                }}>
                <Popover
                    title='更改全局主题'
                    content={
                        <SketchPicker
                            style={{
                                width: '30px',
                                hight: '30px',
                            }}
                            presetColors={['#1890ff', '#25b864', '#ff6f00']}
                            color={color.primaryColor}
                            onChange={({hex}) => {
                                onColorChange({
                                    primaryColor: hex,
                                });
                            }}
                        />}>
                    <Button>更改主题色</Button>
                </Popover>
                <Popover placement="bottom" content={<PassModalForm/>}
                         trigger="click">
                    <Button type="text" style={{border: '2px dashed red'}}
                            icon={<UserOutlined/>}>{getLoginName()}</Button>
                </Popover>
                <Button type="primary" danger onClick={() => {
                    removeToken();
                    /**
                     * 发起退出登录请求
                     */
                    navigate('/login')
                }
                }>
                    登出
                    <PoweroffOutlined/>
                </Button>
            </Space>
        </Header>
    )
}

const PassModalForm = () => {
    return (<ModalForm title="修改密码" width={420} trigger={
        <Button type="primary">
            <EditOutlined/>
            修改密码
        </Button>
    }
                       autoFocusFirstInput
                       modalProps={{
                           onCancel: () => console.log('run'),
                       }} submitTimeout={1000} onFinish={async (values) => {
        await waitTime(1000);
        request.post({
            url: "sys-user/resetPassword",
            data: values,
            succ: (data) => {
                message.success("密码修改成功")
            },
        })
        return true;
    }}>
        <ProForm.Group>
            <ProFormText.Password name="password" label="新密码" placeholder="新密码"
                                  rules={[{required: true, message: '新密码必填!'}]}/>
            <ProFormText.Password name="confirmPassword" label="确认密码" placeholder="确认密码"
                                  dependencies={['password']}
                                  rules={[
                                      {
                                          required: true,
                                          message: '请确认您的密码!',
                                      },
                                      ({getFieldValue}) => ({
                                          validator(_, value) {
                                              if (!value || getFieldValue('password') === value) {
                                                  return Promise.resolve();
                                              }

                                              return Promise.reject(new Error('您两次输入的密码不匹配！'));
                                          },
                                      }),
                                  ]}/>
            <ProFormText hidden name="id" initialValue={getLoginObj().id}/>
        </ProForm.Group>
    </ModalForm>);
};

export default CustomHeader